import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getStoreInfo, addStoreInfo, deleteStoreInfo, editStoreInfo } from '@/api/store'
import type { DepartmentItem, AddDepartmentParams, UpdateDepartmentParams } from '@/api/types/department'
import { ElMessage } from 'element-plus'

export const useStore = defineStore('store', () => {
    const departmentList = ref<[] |any >([])
    const loading = ref(false)

    // 获取门店列表
    const fetchDepartmentList = async () => {
        loading.value = true
        try {
            const response = await getStoreInfo()
            if (response.code === '200') {
                departmentList.value = response.result
            } else {
                ElMessage.error(response.msg || '获取部门列表失败')
            }
        } catch (error) {
            console.error('获取部门列表失败:', error)
            ElMessage.error('获取部门列表失败')
        } finally {
            loading.value = false
        }
    }

    // 新增部门
    const addDepartmentAction = async (data: AddDepartmentParams) => {
        try {
            const response = await addStoreInfo(data)
            if (response.code === '200') {
                ElMessage.success(response.msg || '新增成功')
                await fetchDepartmentList()
                return true
            } else {
                ElMessage.error(response.msg || '新增失败')
                return false
            }
        } catch (error) {
            console.error('新增部门失败:', error)
            ElMessage.error('新增部门失败')
            return false
        }
    }

    // 编辑部门
    const updateDepartmentAction = async (data: UpdateDepartmentParams) => {
        try {
            const response = await editStoreInfo(data)
            if (response.code === '200') {
                ElMessage.success(response.msg || '修改成功')
                await fetchDepartmentList()
                return true
            } else {
                ElMessage.error(response.msg || '修改失败')
                return false
            }
        } catch (error) {
            console.error('编辑部门失败:', error)
            ElMessage.error('编辑部门失败')
            return false
        }
    }

    // 删除门店
    const deleteDepartmentAction = async (pid: number, selfid: number) => {
        try {
            const response = await deleteStoreInfo(pid, selfid )
            if (response.code === '200') {
                ElMessage.success(response.msg || '删除成功')
                await fetchDepartmentList()
                return true
            } else {
                ElMessage.error(response.msg || '删除失败')
                return false
            }
        } catch (error) {
            console.error('删除门店失败:', error)
            ElMessage.error('删除门店失败')
            return false
        }
    }

    return {
        departmentList,
        loading,
        fetchDepartmentList,
        addDepartment: addDepartmentAction,
        updateDepartment: updateDepartmentAction,
        deleteDepartment: deleteDepartmentAction
    }
})
